<?php

namespace app\api\controller;


use app\api\BaseController;
use app\api\middleware\Auth;
use app\api\validate\Register;
use app\api\validate\RegisterValidate;
use think\exception\ValidateException;
use think\facade\Db;

class Pcuser extends BaseController
{
    protected $middleware = [
        Auth::class => ['except' 	=> ['register','getWechatInfoByAPP','phoneLogin','forgetPwd','codeLogin'] ]
    ];

    /**
     * 微信登陆(app)
     */
    public function getWechatInfoByAPP()
    {
        $code = request()->param('code');
        $app_id = config('config.wechat.app_appid'); // 开放平台APP的id
        $app_secret = config('config.wechat.app_secret'); // 开放平台APP的secret
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$app_id}&secret={$app_secret}&code={$code}&grant_type=authorization_code";
        $data = curl_get($url);
        $data =json_decode($data,true);
        if (!isset($data['openid'])) {
            return error($data['errmsg']);
        }
        //是否注册
        $user = Db::name('user')->where('openid',$data['openid'])->find();
        $index = new Index();
        if (!empty($user)) {
            $token = $index->getToken($user['id']);
            return json(['code'=>0,'msg'=>'登录成功','data'=>$user,'token'=>$token]);
        }
        $add = [
            'nickname' => '用户'.get_random_str(5,3),
            'avatar' => '/static/admin/images/logo.jpg',
            'openid' => $data['openid'],
            'distinct_code' => get_random_str(6,6),
            'register_time' => time()
        ];
        $user_id = Db::name('user')->insertGetId($add);
        $user = Db::name('user')->where('id',$user_id)->find();
        $token = $index->getToken($user['id']);
        return json(['code'=>0,'msg'=>'登录成功','data'=>$user,'token'=>$token]);
    }

    /**
     * 绑定微信
     */
    public function bindWechat()
    {
        //当前账号是否绑定微信
        $currentUser = Db::name('user')->where('id',JWT_UID)->find();
        if (!empty($currentUser['openid'])) {
            return error('当前账号已绑定微信');
        }
        $code = request()->param('code');
        $app_id = config('config.wechat.app_appid'); // 开放平台APP的id
        $app_secret = config('config.wechat.app_secret'); // 开放平台APP的secret
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$app_id}&secret={$app_secret}&code={$code}&grant_type=authorization_code";
        $data = curl_get($url);
        $data =json_decode($data,true);
        if (!isset($data['openid'])) {
            return error($data['errmsg']);
        }
        //当前微信是否绑定其它账号
        $user = Db::name('user')->where('openid',$data['openid'])->find();
        if (!empty($user)) {
            return error('当前微信已绑定其它账号');
        }
        //账号绑定
        Db::name('user')->where('id',$currentUser['id'])->update(['openid'=>$data['openid'],'wx_time'=>time()]);
        return success('绑定成功');
    }

    /**
     * 注册账号
     */
    public function register()
    {

        $param = get_params();
        try {
            validate(Register::class)->check($param);
            //验证码校验
            $code = cache('register_code_'.$param['mobile']); //9307
            if ($code != $param['captcha']) {
                return json(['code'=>1,'msg'=>'验证码错误']);
            }
            cache('register_code_'.$param['mobile'],null);
            $user = Db::name('user')->where('mobile',$param['mobile'])->find();
            if (!empty($user)) {
                return error('当前手机号已注册');
            }
            if (!empty($param['distinct_code'])) {
                $distinct_user = Db::name('user')->where(['distinct_code'=>$param['distinct_code']])->find();
                if (!empty($distinct_user)) {
                    $param['pid'] = $distinct_user['id'];
                }
            }
            $param['nickname'] = '用户'.get_random_str(5,3);
//            $param['distinct_code'] = get_random_str(6,6);
            $param['avatar'] = '/static/admin/images/logo.jpg';
            $param['register_time'] = time();
            $userInfo = \app\admin\model\User::create($param);
            // 生成 token（确保每次登录都唯一）
            $index = new Index();
            $token = $index->getToken($userInfo->id);
            Db::name('user')->where('id', $userInfo->id)->update(['token' => $token]);
            return success('注册成功');
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return error($e->getError());
        }
    }

    /**
     * 手机号密码登录
     */
    /*public function phoneLogin()
    {
        if (request()->isPost()) {
            $param = get_params();
            if (empty($param['mobile']) || empty($param['password'])) {
                return json(['code'=>1,'msg'=>'参数错误']);
            }
            $user = Db::name('user')->where(['mobile'=>$param['mobile']])->find();
            if (empty($user)) {
                return json(['code'=>1,'msg'=>'手机号或密码错误']);
            }
            if ($param['password'] !== $user['password']) {
                return json(['code'=>1,'msg'=>'手机号或密码错误']);
            }
            //是否禁用
            if ($user['status'] == 0) {
                return json(['code'=>1,'msg'=>'账号已被禁用']);
            }
            $index = new Index();
            $token = $index->getToken($user['id']);
            return json(['code'=>0,'msg'=>'登录成功','data'=>$user,'token'=>$token]);
        }
    }*/
    public function phoneLogin() {
        if (request()->isPost()) {
            $param = get_params();
            if (empty($param['mobile']) || empty($param['password'])) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }
    
            $user = Db::name('user')->where(['mobile' => $param['mobile']])->find();
            if (empty($user)) {
                return json(['code' => 1, 'msg' => '手机号或密码错误']);
            }
    
            if ($param['password'] !== $user['password']) {
                return json(['code' => 1, 'msg' => '手机号或密码错误']);
            }
    
            if ($user['status'] == 0) {
                return json(['code' => 1, 'msg' => '账号已被禁用']);
            }
    
            // 生成 token（确保每次登录都唯一）
            $index = new Index();
            $token = $index->getToken($user['id']);
    
            // 保存 token 到数据库（覆盖旧的）
            Db::name('user')->where('id', $user['id'])->update(['token' => $token]);
    
            // 移除密码字段返回
            unset($user['password']);
            $user['token'] = $token;
    
            return json(['code' => 0, 'msg' => '登录成功', 'data' => $user]);
        }
    }
    
     /**
      * 验证token
     *  pcuser/checkToken
     */
    public function checkToken() {
        $token = request()->header('token');
        $uid = 0;
        if(empty($token)) {
             return json(['code' => 401, 'msg' => '账号已在其他设备登录', 'data' => $user]);
        }
       
        $checkResult = Index::checkToken($token);
        $res = json_decode($checkResult->getContent(), true);
        if ($res['code'] == 1) {
            $uid = $res['data']['userid'];
        }
        
        $realToken = Db::name('user')->where('id', $uid)->value('token');
        if ($realToken !== $token) {
            return json(['code' => 401, 'msg' => '账号已在其他设备登录', 'data' => $user]);
        }
        return json(['code' => 0, 'msg' => '登录成功', 'data' => $user]);
    }


    /**
     * 找回密码
     */
    public function forgetPwd()
    {
        if (request()->isPost()) {
            $param = get_params();
            try {
                validate(Register::class)->check($param);
                //验证码校验
                $code = cache('register_code_'.$param['mobile']); //9307
                if ($code != $param['captcha']) {
                    return json(['code'=>1,'msg'=>'验证码错误']);
                }
                cache('register_code_'.$param['mobile'],null);
                $user = Db::name('user')->where('mobile',$param['mobile'])->find();
                if (empty($user)) {
                    return error('当前手机号未注册');
                }
                \app\admin\model\User::update($param,['id'=>$user['id']]);
                return success('修改成功');
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return error($e->getError());
            }
        }
    }

    /**
     * 修改密码
     */
    public function editPwd()
    {
        $param = get_params();
        if (empty($param['code'])) {
            return error('短信验证码不能为空');
        }
        $user = Db::name('user')->where('id',JWT_UID)->find();
        //验证码校验
        $code = cache('register_code_'.$user['mobile']);
        if ($code != $param['code']) {
            return json(['code'=>1,'msg'=>'验证码错误']);
        }
        try {
            validate(RegisterValidate::class)->check($param);
            if ($user['password'] != $param['old_password']) {
                return error('旧密码错误');
            }
            \app\admin\model\User::update($param,['id'=>$user['id']]);
            return success('修改成功');
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return error($e->getError());
        }
    }

    /**
     * 注销账号
     */
    public function delUser()
    {
        Db::name('user')->where('id',JWT_UID)->delete();
        return success('注销成功');
    }

    /**
     * 验证码登录
     */
    public function codeLogin()
    {
        if (request()->isPost()) {
            $param = get_params();
            if (empty($param['mobile']) || empty($param['captcha'])) {
                return json(['code'=>1,'msg'=>'手机号或验证码不能为空']);
            }
            $code = cache('register_code_'.$param['mobile']); //9307
            if ($code != $param['captcha']) {
                return json(['code'=>1,'msg'=>'验证码错误']);
            }
            $user = Db::name('user')->where('mobile',$param['mobile'])->find();
            if (empty($user)) {
                return error('该手机号未注册');
            }
            $index = new Index();
            $token = $index->getToken($user['id']);
            return json(['code'=>0,'msg'=>'登录成功','data'=>$user,'token'=>$token]);
        }
    }

}